package com.fwtai;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.CorsHandler;
import io.vertx.ext.web.handler.StaticHandler;

import java.util.HashSet;
import java.util.Set;

/**
 * 文件上传
*/
public class UploadVerticle extends AbstractVerticle{

  @Override
  public void start(final Promise<Void> startPromise) throws Exception{
    Router router = Router.router(vertx);
    final Set<HttpMethod> allowMethods = new HashSet<>();
    final Set<String> allowHeaders = new HashSet<>();
    allowMethods.add(HttpMethod.GET);
    allowMethods.add(HttpMethod.POST);
    allowMethods.add(HttpMethod.DELETE);
    allowMethods.add(HttpMethod.PUT);
    allowHeaders.add("Content-Type");
    allowHeaders.add("token");
    router.route("/*").handler(CorsHandler.create("*").allowedHeaders(allowHeaders).allowedMethods(allowMethods));
    router.route("/my/uploadimage/*").handler(BodyHandler.create().setUploadsDirectory("mines").setBodyLimit(1000000)).handler(StaticHandler.create().setWebRoot("mines").setCachingEnabled(false).setDirectoryListing(false));
    router.post("/my/uploadimage/").handler(ctx -> {
      ctx.response().setChunked(true);
      for(FileUpload f : ctx.fileUploads()){
        vertx.fileSystem().move(f.uploadedFileName(),"./mines/" + f.fileName(),res -> {
          if(res.succeeded()){
            System.out.println("upload success.");
          }else{
            res.cause().printStackTrace();
          }
        });
      }
      ctx.response().end("upload success.");
    });
    vertx.createHttpServer().requestHandler(router).listen(2233);
    startPromise.complete();
  }

  public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();
    vertx.deployVerticle(UploadVerticle.class.getName());
  }
}